<?php
namespace app\backmanage\controller;

use app\common\model\common\AuthAccountConfigs as Model;
use thans\layuiAdmin\facade\AdminsAuth;
use thans\layuiAdmin\facade\Json;
use thans\layuiAdmin\facade\Utils;
use thans\layuiAdmin\Form;
use thans\layuiAdmin\Table;
use thans\layuiAdmin\Traits\FormActions;
use think\Request;

class AuthAccountConfig extends Base
{
    use FormActions;

    protected $route_alias = 'AuthAccountConfig';
    protected $title       = '三方授权账号管理';

    public function list(Request $request)
    {
        if ($request->isAjax()||$request->isPost()) {
            list($where, $order, $page, $limit) = Utils::buildParams('id|create_time');

            $model  = new Model();
            $where[] = ['status','=',1];
            list($partitionId,$partitions)=\app\common\model\common\PartitionPackage::getPartitionPackageInfo();
            $partitionIds=array_keys($partitions);
            $list  = $model->where($where)->whereIn('partition_id',$partitionIds)->page($page, $limit)->order($order)->field('*')->select();
            $count = $model->where($where)->whereIn('partition_id',$partitionIds)->count();
            //获取分区名称信息
            //$partitions=(new \app\common\model\common\SignPackage)->where('status',1)->column('partition_name','partition_id');

            //数据库信息
            foreach ($list as $k=>$v){
                $list[$k]['partition_name']=$partitions[$v['partition_id']]??'';
                $list[$k]['google_info'] = sprintf("app_id：%s<br>app_secret：%s",$v['google_app_id']??'',$v['google_app_secret']??'');
                $list[$k]['facebook_info'] = sprintf("app_id：%s<br>app_secret：%s",$v['facebook_app_id']??'',$v['facebook_app_secret']??'');
                $list[$k]['twitter_info'] = sprintf("app_id：%s<br>app_secret：%s",$v['twitter_app_id']??'',$v['twitter_app_secret']??'');
                $list[$k]['qq_info'] = sprintf("app_id：%s<br>app_secret：%s",$v['qq_app_id']??'',$v['qq_app_secret']??'');
                $list[$k]['line_info'] = sprintf("app_id：%s<br>app_secret：%s",$v['line_app_id']??'',$v['line_app_secret']??'');
            }
            Json::success('获取成功', $list, ['total' => $count,'count' => $count]);
        }
        $tb = new Table();
        $tb->url(url('\backmanage\\' . $this->route_alias . '\\list'));
        $tb->column('id', '自增ID',90);
        $tb->column('partition_id', '分区ID',100);
        $tb->column('partition_name', '分区名称',150);
        $tb->column('google_info', 'Google信息',150);
        $tb->column('facebook_info', 'Facebook信息',200);
        $tb->column('twitter_info', 'Twitter信息',200);
        $tb->column('line_info', 'Line信息',200);
        $tb->column('qq_info', 'QQ信息',200);
        $tb->column('create_time', '创建时间');
        $tb->column('update_time', '更新时间');

        $url = url('\backmanage\\' . $this->route_alias . '\\create');
        if (AdminsAuth::check($url)) {
            $tb->action('新增', $url);
        }
        $url = url('\backmanage\\' . $this->route_alias . '\\edit', ['id' => '{{ d.id }}']);
        if (AdminsAuth::check($url)) {
            $tb->tool('编辑', $url, 'formLayer');
        }
        $url = url('\backmanage\\' . $this->route_alias . '\\delete', ['id' => '{{ d.id }}']);
        if (AdminsAuth::check($url, 'DELETE')) {
            $tb->tool('删除', $url, 'confirmAjax', 'danger', 'DELETE');
        }
        $tb->title($this->title);

        return $tb->render();
    }
    public function delete(Request $request)
    {
        if($request->isDelete()){
            $res = Model::update(['id' => $request->param('id'),'status'=>2]);
            return json(['code' => 0, 'message' => '删除成功', 'data' => $res]);
        }
    }
    private function buildForm()
    {
        $model = new Model();
        $form  = new Form($model);

        $partitions= \app\common\model\common\PartitionPackage::getPartitionPackageOptions();
        $form->select()->name('partition_id')->label('分区')->options($partitions);

        $form->text()->name('google_app_id')->label('Google APPID')->placeholder('请输入Google APPID');
        $form->text()->name('google_app_secret')->label('Google APP_SECRET')->placeholder('请输入Google APP_SECRET');

        $form->text()->name('facebook_app_id')->label('Facebook APPID')->placeholder('请输入Facebook APPID');
        $form->text()->name('facebook_app_secret')->label('Facebook APP_SECRET')->placeholder('请输入Facebook APP_SECRET');

        $form->text()->name('twitter_app_id')->label('Twitter APPID')->placeholder('请输入Twitter APPID');
        $form->text()->name('twitter_app_secret')->label('Twitter APP_SECRET')->placeholder('请输入Twitter APP_SECRET');

        $form->text()->name('line_app_id')->label('Line APPID')->placeholder('请输入Line APPID');
        $form->text()->name('line_app_secret')->label('Line APP_SECRET')->placeholder('请输入Line APP_SECRET');

        $form->text()->name('qq_app_id')->label('QQ APPID')->placeholder('请输入QQ APPID');
        $form->text()->name('qq_app_secret')->label('QQ APP_SECRET')->placeholder('请输入QQ APP_SECRET');

        
        return $form;
    }


    public function update($id, Request $request)
    {
        $param = $request->param();
        if (empty($param['partition_id'])){
            Json::error('分区ID不能为空');
        }
        $ret=(new Model())->where([
            'partition_id' => $param['partition_id'],
            'status' => 1,
            'id' => $id,
        ])->count();
        if (!$ret){
            Json::error('不能改变分区ID值');
        }
        //检测配置情况
        $list=[];
        if ($param['google_app_id'] && $param['google_app_secret']){
            $list[]='Google';
        }
        if ($param['facebook_app_id'] && $param['facebook_app_secret']){
            $list[]='Facebook';
        }
        if ($param['twitter_app_id'] && $param['twitter_app_secret']){
            $list[]='Twitter';
        }
        if ($param['line_app_id'] && $param['line_app_secret']){
            $list[]='Line';
        }
        if ($param['qq_app_id'] && $param['qq_app_secret']){
            $list[]='QQ';
        }
        $threeAuthLoginConfig=implode(',',$list);
        $signPackageConfig=\app\common\model\common\PartitionPackage::where('partition_id',$param['partition_id'])->find()->toArray();
        getSwitchDatabaseModel(
            $param['partition_id'],
            $signPackageConfig['api_mysql_host_name'],
            $signPackageConfig['api_mysql_database'],
            $signPackageConfig['api_mysql_username'],
            $signPackageConfig['api_mysql_password'],
            $signPackageConfig['api_mysql_hostport']
        )->table('config')->where('name','threeAuthLoginConfig')->where('status',1)->update([
            'value' => $threeAuthLoginConfig,
            'update_time'=>time()
        ]);
        $this->buildForm($request)->update($id, $param);
    }


    public function save(Request $request)
    {
        $param = $request->param();
        if (empty($param['partition_id'])){
            Json::error('分区ID不能为空');
        }
        //不能重复添加同一分区
        $ret=(new Model())->where([
            'partition_id' => $param['partition_id'],
            'status' => 1
        ])->count();
        if ($ret){
            Json::error('系统内已存在重复分区ID');
        }
        //检测配置情况
        $list=[];
        if ($param['google_app_id'] && $param['google_app_secret']){
            $list[]='Google';
        }
        if ($param['facebook_app_id'] && $param['facebook_app_secret']){
            $list[]='Facebook';
        }
        if ($param['twitter_app_id'] && $param['twitter_app_secret']){
            $list[]='Twitter';
        }
        if ($param['line_app_id'] && $param['line_app_secret']){
            $list[]='Line';
        }
        if ($param['qq_app_id'] && $param['qq_app_secret']){
            $list[]='QQ';
        }
        $threeAuthLoginConfig=implode(',',$list);
        $signPackageConfig=\app\common\model\common\PartitionPackage::where('partition_id',$param['partition_id'])->find()->toArray();
        getSwitchDatabaseModel(
            $param['partition_id'],
            $signPackageConfig['api_mysql_host_name'],
            $signPackageConfig['api_mysql_database'],
            $signPackageConfig['api_mysql_username'],
            $signPackageConfig['api_mysql_password'],
            $signPackageConfig['api_mysql_hostport']
        )->table('config')->where('name','threeAuthLoginConfig')->where('status',1)->update([
            'value' => $threeAuthLoginConfig,
            'update_time'=>time()
        ]);
        $this->buildForm($request)->save($param);
    }
}
